package com.lottery.game.core.modules.service.app.v2.impl;


import com.lottery.game.common.exception.BaseException;
import com.lottery.game.common.utils.MD5Util;
import com.lottery.game.core.modules.service.app.v2.SignService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SignServiceImpl implements SignService {

    public static final String SIGN_KEY = "sign";

    @Override
    public String getSign(Map<String, String> paramMap, String key) {
        List<String> paramsList = paramMap.entrySet().stream().map(entry -> entry.getKey() + "=" + String.valueOf(entry.getValue())).collect(Collectors.toList());
        String[] paramsList_ = paramsList.toArray(new String[paramsList.size()]);
        Arrays.sort(paramsList_);
        StringBuffer sb = new StringBuffer();
        for (String keyAndValue : paramsList_) {
            sb.append(keyAndValue).append("&");
        }
        //  直接 MD5 对key  生成 签名
        return MD5Util.MD532(sb.toString() + ("key=" + key));
    }

    @Override
    public Map<String, String> checkSign(Map<String, String> paramMap, String sign, String key) {
        // 做一个副本来操作
        Map<String,String> paramMap_ = new HashMap<>(paramMap);
        paramMap_.remove(SIGN_KEY);
        if (!this.getSign(paramMap_, key).equals(sign)) {
            log.info(this.getSign(paramMap_, key)+"==============="+sign);
            throw new BaseException(1001, "签名认证异常");
        }
        // 没有 任何 异常 就 把这个 map 返回
        return paramMap;
    }
}
